<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>计算属性</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.min.js"></script>
</head>
<body>
    <div id="app">
        商品：<input type="text" v-model="name"><br>
        数量：<input type="text" v-model="count"><br>
        价格：<input type="text" v-model="price"><br>
        <button @click="add">添加到购物车</button>
        <hr>
        <ul>
            <li v-for="item in list" v-text="item.name+'的数量是'+
            item.count+',单价是'+item.price+',小计：'+item.sum"></li>
            <li>总计：总数----{{sumcount}} 总价---{{tosum}}</li>
        </ul>
    </div>
</body>
<script>
    var vue = new Vue({
        el: '#app',
        data: {
                name:'',
                count:'',
                price:'',
                sum: 0,
            list: [{name:'牙刷',count:5,price:10,sum:50},
            {name:'牙膏',count:2,price:20,sum:40},
            {name:'镜子',count:3,price:30,sum:90}]
        },
        methods: {
            add(){
                this.sum = this.count * this.price
                var goods = {name:this.name,count:this.count,price:this.price,sum:this.sum}
                this.list.push(goods)
                this.name=''
                this.count=''
                this.price=''
            }
        },
        computed: {
            sumcount(){
                return this.list.reduce((total,b)=>{
                    return total + Number(b.count)
                },0)
            },
            tosum(){
                return this.list.reduce((total,b)=>{
                    return total + Number(b.sum)
                },0)
            }
        }
    })
</script>
</html>